package com.yunhe.merchants.service.impl;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.ser.Serializers;
import com.yunhe.common.exception.ArgumentErrorException;
import com.yunhe.common.model.ResultObject;
import com.yunhe.common.model.authority.Organization;
import com.yunhe.common.model.authority.User;
import com.yunhe.common.model.office.Office;
import com.yunhe.common.util.DateTimeUtils;
import com.yunhe.common.util.RedisClient;
import com.yunhe.common.util.StringUtil;
import com.yunhe.merchants.client.AuthorityClient;
import com.yunhe.merchants.constant.MyProjectConsts;
import com.yunhe.merchants.domain.DeptPlanData;
import com.yunhe.merchants.domain.SalesmanPlanData;
import com.yunhe.merchants.model.*;
import com.yunhe.merchants.repository.DeptPlanDataRepository;
import com.yunhe.merchants.repository.MyProjectRepository;
import com.yunhe.merchants.repository.ProcessStatusRepository;
import com.yunhe.merchants.repository.SalesmanPlanDataRepository;
import com.yunhe.merchants.service.IPlanService;
import com.yunhe.merchants.util.MyHeaderUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import com.yunhe.common.util.CollectionUtil;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @ClassName: PlanServiceImpl
 * @Description:
 * @author: GongDaCheng
 * @Date: 15:01 2021/4/28
 */
@Service
public class PlanServiceImpl implements IPlanService {
    @Autowired
    DeptPlanDataRepository deptPlanDataRepository;
    @Autowired
    SalesmanPlanDataRepository salesmanPlanDataRepository;
    @Autowired
    MyProjectRepository myProjectRepository;
    @Autowired
    private RedisClient redisClient;
    @Autowired
    private MyHeaderUtil myHeaderUtil;
    @Autowired
    private AuthorityClient authorityClient;
    @Autowired
    private ProcessStatusRepository processStatusRepository;


    @Override
    public int makeDeptPlan(List<DeptPlan> deptPlanList) {
        List<DeptPlanData> deptPlanDataList = new ArrayList<>();
        for (DeptPlan deptPlan : deptPlanList) {
            Long deptId = deptPlan.getId();
            String year = deptPlan.getYearPlan().getTimeVal();
            //获取部门年度计划
            getDeptPlanData(deptPlanDataList, Arrays.asList(deptPlan.getYearPlan()), MyProjectConsts.Time_Type.Year.value(), year, deptId);
            //获取部门季度计划
            if (!CollectionUtil.isEmpty(deptPlan.getQuarterPlan())){
                getDeptPlanData(deptPlanDataList, deptPlan.getQuarterPlan(), MyProjectConsts.Time_Type.Quarter.value(), year, deptId);
            }
            //获取部门月度计划
            if (!CollectionUtil.isEmpty(deptPlan.getMonthPlan())){
                getDeptPlanData(deptPlanDataList, deptPlan.getMonthPlan(), MyProjectConsts.Time_Type.Month.value(), year, deptId);
            }
        }
        for (DeptPlanData deptPlanData : deptPlanDataList) {
            deptPlanDataRepository.insert(deptPlanData);
        }
        return deptPlanDataList.size();
    }

    @Override
    public List<DeptPlan> getDeptPlan(String year) throws ArgumentErrorException {
        List<DeptPlan>  deptPlans = new ArrayList<>();
        Long userId = myHeaderUtil.getHeaderUser();
        if(userId == null){
            throw new ArgumentErrorException("登录信息已失效,请重新登录");
        }
        //查询当前登录人的组织以及子组织
        List<Long> orgIds = subOrg(userId);
        //通过部门查询部门计划
        List<DeptPlanData> deptPlanDatas = deptPlanDataRepository.getDeptPlans(orgIds, year);
        if(!CollectionUtil.isEmpty(deptPlanDatas)){
            //分组
            // 部门分组
            Map<Long, List<DeptPlanData>> orgPlanMap = deptPlanDatas.stream().collect(Collectors.groupingBy(DeptPlanData::getDeptId, Collectors.toList()));
            if(!CollectionUtil.isEmpty(orgPlanMap)){
                for (Map.Entry<Long, List<DeptPlanData>> entry : orgPlanMap.entrySet()) {
                    DeptPlan deptPlan = new DeptPlan();
                    deptPlan.setId(entry.getKey());
                    List<DeptPlanData> values = entry.getValue();
                    //年 过滤 封装
                    List<DeptPlanData> yearDatas = values.stream().filter(value -> {
                        return MyProjectConsts.Time_Type.Year.value().equals(value.getType());
                    }).collect(Collectors.toList());
                    BasePlan yearPlan = new BasePlan();
                    yearPlan.setTimeVal(year);
                    yearPlan.setContractedArea(yearDatas.get(0).getContractedArea());
                    yearPlan.setVisitorCount(yearDatas.get(0).getVisitorCount());
                    yearPlan.setCallerCount(yearDatas.get(0).getCallerCount());
                    yearPlan.setNetworkPromotionCount(yearDatas.get(0).getNetworkPromotionCount());
                    deptPlan.setYearPlan(yearPlan);
                    //季 过滤
                    List<DeptPlanData> quarterDatas = values.stream().filter(value -> {
                        return MyProjectConsts.Time_Type.Quarter.value().equals(value.getType());
                    }).collect(Collectors.toList());
                    List<BasePlan> quarterPlans = new ArrayList<>();
                    for (int i = 0; i < quarterDatas.size(); i++) {
                        DeptPlanData deptQuarterPlanData = quarterDatas.get(i);
                        BasePlan quarterPlan = new BasePlan();
                        quarterPlan.setTimeVal(deptQuarterPlanData.getQuarter());
                        quarterPlan.setContractedArea(deptQuarterPlanData.getContractedArea());
                        quarterPlan.setVisitorCount(deptQuarterPlanData.getVisitorCount());
                        quarterPlan.setCallerCount(deptQuarterPlanData.getCallerCount());
                        quarterPlan.setNetworkPromotionCount(deptQuarterPlanData.getNetworkPromotionCount());
                        quarterPlans.add(quarterPlan);
                    }
                    deptPlan.setQuarterPlan(quarterPlans);
                    //月 过滤
                    List<DeptPlanData> monthDatas = values.stream().filter(value -> {
                        return MyProjectConsts.Time_Type.Month.value().equals(value.getType());
                    }).collect(Collectors.toList());
                    List<BasePlan> monthPlans = new ArrayList<>();
                    for (int i = 0; i < monthDatas.size(); i++) {
                        DeptPlanData deptMonthPlanData = monthDatas.get(i);
                        BasePlan monthPlan = new BasePlan();
                        monthPlan.setTimeVal(deptMonthPlanData.getMonth());
                        monthPlan.setContractedArea(deptMonthPlanData.getContractedArea());
                        monthPlan.setVisitorCount(deptMonthPlanData.getVisitorCount());
                        monthPlan.setCallerCount(deptMonthPlanData.getCallerCount());
                        monthPlan.setNetworkPromotionCount(deptMonthPlanData.getNetworkPromotionCount());
                        monthPlans.add(monthPlan);
                    }
                    deptPlan.setMonthPlan(monthPlans);
                    deptPlans.add(deptPlan);
                }
            }
        }
        return deptPlans;
    }

    @Override
    public Statistics deptPlanStatistics(List<Long> deptIds, String type, String year, String quarter, String month) {
        Statistics statistics = new Statistics();
        if ("2".equals(type)){
            quarter = null;
        }
        //当前时间指标
        DeptPlanData currentDeptPlanData = deptPlanDataRepository.getDeptPlan(deptIds,type,year,quarter,month);
        getStatistics(deptIds,null,type,year,quarter,month,statistics,null,currentDeptPlanData);
        return statistics;
    }

    @Override
    public int makeSalesmanPlan(List<SalesmanPlan> salesmanPlanList) throws ArgumentErrorException {
        List<SalesmanPlanData> salesmanPlanDataList = new ArrayList<>();
        for (SalesmanPlan salesmanPlan : salesmanPlanList) {
            Long salesmanId = salesmanPlan.getId();
            String year = salesmanPlan.getYearPlan().getTimeVal();
            //获取业务员年度计划
            getSalesmanPlanData(salesmanPlanDataList,Arrays.asList(salesmanPlan.getYearPlan()),MyProjectConsts.Time_Type.Year.value(),year,salesmanId);
            //获取业务员季度计划
            if (!CollectionUtil.isEmpty(salesmanPlan.getQuarterPlan())){
                getSalesmanPlanData(salesmanPlanDataList,salesmanPlan.getQuarterPlan(),MyProjectConsts.Time_Type.Quarter.value(),year,salesmanId);
            }
            //获取业务员月度计划
            if (!CollectionUtil.isEmpty(salesmanPlan.getMonthPlan())){
                getSalesmanPlanData(salesmanPlanDataList,salesmanPlan.getMonthPlan(),MyProjectConsts.Time_Type.Month.value(),year,salesmanId);
            }
        }
        for (SalesmanPlanData salesmanPlanData : salesmanPlanDataList) {
            salesmanPlanDataRepository.insert(salesmanPlanData);
        }
        return salesmanPlanDataList.size();
    }

    @Override
    public List<SalesmanPlan> getSalesmanPlan(String year) throws ArgumentErrorException {
        List<SalesmanPlan> salesmanPlans = new ArrayList<>();
        Long headerUser = myHeaderUtil.getHeaderUser();
        if(headerUser == null){
            throw new ArgumentErrorException("登录信息已失效,请重新登录");
        }
        String orgIdStr = redisClient.get("Org:" + headerUser);
        List<SalesmanPlanData> salesmanPlanDatas = salesmanPlanDataRepository.selectSalesmanPlanDataByYearAndOrg(year,Long.parseLong(orgIdStr.split("-")[0]));
        if(!CollectionUtil.isEmpty(salesmanPlanDatas)){
            //分组
            // 部门分组
            Map<Long, List<SalesmanPlanData>> orgPlanMap = salesmanPlanDatas.stream().collect(Collectors.groupingBy(SalesmanPlanData::getSalesmanId, Collectors.toList()));
            if(!CollectionUtil.isEmpty(orgPlanMap)){
                for (Map.Entry<Long, List<SalesmanPlanData>> entry : orgPlanMap.entrySet()) {
                    SalesmanPlan salesmanPlan = new SalesmanPlan();
                    salesmanPlan.setId(entry.getKey());
                    List<SalesmanPlanData> values = entry.getValue();
                    salesmanPlan.setDeptId(values.get(0).getOrgId());
                    //年 过滤 封装
                    List<SalesmanPlanData> yearDatas = values.stream().filter(value -> {
                        return MyProjectConsts.Time_Type.Year.value().equals(value.getType());
                    }).collect(Collectors.toList());
                    BasePlan yearPlan = new BasePlan();
                    yearPlan.setTimeVal(year);
                    yearPlan.setContractedArea(yearDatas.get(0).getContractedArea());
                    yearPlan.setVisitorCount(yearDatas.get(0).getVisitorCount());
                    yearPlan.setCallerCount(yearDatas.get(0).getCallerCount());
                    yearPlan.setNetworkPromotionCount(yearDatas.get(0).getNetworkPromotionCount());
                    salesmanPlan.setYearPlan(yearPlan);
                    //季 过滤
                    List<SalesmanPlanData> quarterDatas = values.stream().filter(value -> {
                        return MyProjectConsts.Time_Type.Quarter.value().equals(value.getType());
                    }).collect(Collectors.toList());
                    List<BasePlan> quarterPlans = new ArrayList<>();
                    for (int i = 0; i < quarterDatas.size(); i++) {
                        SalesmanPlanData salesmanPlanData = quarterDatas.get(i);
                        BasePlan quarterPlan = new BasePlan();
                        quarterPlan.setTimeVal(salesmanPlanData.getQuarter());
                        quarterPlan.setContractedArea(salesmanPlanData.getContractedArea());
                        quarterPlan.setVisitorCount(salesmanPlanData.getVisitorCount());
                        quarterPlan.setCallerCount(salesmanPlanData.getCallerCount());
                        quarterPlan.setNetworkPromotionCount(salesmanPlanData.getNetworkPromotionCount());
                        quarterPlans.add(quarterPlan);
                    }
                    salesmanPlan.setQuarterPlan(quarterPlans);
                    //月 过滤
                    List<SalesmanPlanData> monthDatas = values.stream().filter(value -> {
                        return MyProjectConsts.Time_Type.Month.value().equals(value.getType());
                    }).collect(Collectors.toList());
                    List<BasePlan> monthPlans = new ArrayList<>();
                    for (int i = 0; i < monthDatas.size(); i++) {
                        SalesmanPlanData salesmanPlanData = monthDatas.get(i);
                        BasePlan monthPlan = new BasePlan();
                        monthPlan.setTimeVal(salesmanPlanData.getMonth());
                        monthPlan.setContractedArea(salesmanPlanData.getContractedArea());
                        monthPlan.setVisitorCount(salesmanPlanData.getVisitorCount());
                        monthPlan.setCallerCount(salesmanPlanData.getCallerCount());
                        monthPlan.setNetworkPromotionCount(salesmanPlanData.getNetworkPromotionCount());
                        monthPlans.add(monthPlan);
                    }
                    salesmanPlan.setMonthPlan(monthPlans);
                    salesmanPlans.add(salesmanPlan);
                }
            }
        }

        return salesmanPlans;
    }

    @Override
    public Statistics salesmanPlanStatistics(Long deptId, Long salesmanId, String type, String year, String quarter, String month) {
        Statistics statistics = new Statistics();
        if ("2".equals(type)){
            quarter = null;
        }
        //当前时间指标
        SalesmanPlanData currentSalesmanPlanData = salesmanPlanDataRepository.getSalesmanPlan(deptId, salesmanId, type, year, quarter, month);
        getStatistics(Arrays.asList(deptId),salesmanId,type,year,quarter,month,statistics,currentSalesmanPlanData,null);
        return statistics;
    }

    @Override
    public Statistics parkPlanStatistics(String type, String year, String quarter, String month) throws ArgumentErrorException {
        Statistics parkStatistics = new Statistics();
        List<Statistics> statisticsList = new ArrayList<>();
        Long userId = myHeaderUtil.getHeaderUser();
        if(userId == null){
            throw new ArgumentErrorException("登录信息已失效,请重新登录");
        }
        //查询当前登录人的组织以及子组织
        List<Long> orgIds = subOrg(userId);
        //parkStatistics = deptPlanStatistics(orgIds, type, year, quarter, month);
        parkStatistics = parkPlanStatistics(orgIds,type,year,quarter,month);
        return parkStatistics;
    }

    private Statistics parkPlanStatistics(List<Long> orgIds, String type, String year, String quarter, String month) {
        Statistics statistics = new Statistics();
        //当前时间指标
        List<DeptPlanData> currentDeptPlanDatas = deptPlanDataRepository.getParkPlan(orgIds,type,year,quarter,month);
        DeptPlanData currentDeptPlanData = new DeptPlanData();
        if(!CollectionUtil.isEmpty(currentDeptPlanDatas)){
            currentDeptPlanData.setContractedArea(currentDeptPlanDatas.stream().
                    mapToDouble(currentDeptPlanData1 ->
                            currentDeptPlanData1.getContractedArea() == null ? 0.0 : currentDeptPlanData1.getContractedArea()).sum());
            currentDeptPlanData.setVisitorCount(currentDeptPlanDatas.stream().
                    mapToInt(currentDeptPlanData1 ->
                            currentDeptPlanData1.getVisitorCount() == null ? 0 : currentDeptPlanData1.getVisitorCount()).sum());
            currentDeptPlanData.setCallerCount(currentDeptPlanDatas.stream().
                    mapToInt(currentDeptPlanData1 ->
                            currentDeptPlanData1.getCallerCount() == null ? 0 : currentDeptPlanData1.getCallerCount()).sum());
            currentDeptPlanData.setNetworkPromotionCount(currentDeptPlanDatas.stream().
                    mapToInt(currentDeptPlanData1 ->
                            currentDeptPlanData1.getNetworkPromotionCount() == null ? 0 : currentDeptPlanData1.getNetworkPromotionCount()).sum());
        }
        getStatistics(orgIds,null,type,year,quarter,month,statistics,null,currentDeptPlanData);
        return statistics;
    }


    private BaseStatistics addBaseStatistics(BaseStatistics resStatistics, BaseStatistics baseStatistics){
        resStatistics.setCurrentTarget(resStatistics.getCurrentTarget() + baseStatistics.getCurrentTarget());
        resStatistics.setCurrentComplete(resStatistics.getCurrentComplete() + baseStatistics.getCurrentComplete());
        resStatistics.setCurrentRate(resStatistics.getCurrentRate() + baseStatistics.getCurrentRate());
        resStatistics.setYearChange(resStatistics.getYearChange() + baseStatistics.getYearChange());
        return resStatistics;
    }

    /**
     * @Description 获取当前时间完成量和去年同期完成量
     * @Param Long deptId, Long salesmanId, String type, String year, String quarter, String month,
     * @Param Statistics statistics, SalesmanPlanData currentSalesmanPlanData,DeptPlanData currentDeptPlanData
     * @Return null
     * @Date 2021/5/14 15:35
     */
    private void getStatistics(List<Long> deptIds, Long salesmanId, String type, String year,
                               String quarter, String month, Statistics statistics,
                               SalesmanPlanData currentSalesmanPlanData,DeptPlanData currentDeptPlanData) {
        //处理时间
        String startTime;
        String endTime;
        String lastStartTime;
        String lastEndTime;
        if (MyProjectConsts.Time_Type.Year.value().equals(type)){
            startTime = DateTimeUtils.getFirstDayOfYear(Integer.parseInt(year));
            endTime = DateTimeUtils.getLastDayOfYear((Integer.parseInt(year)));
            lastStartTime = DateTimeUtils.getFirstDayOfYear(Integer.parseInt(year) - 1);
            lastEndTime = DateTimeUtils.getLastDayOfYear(Integer.parseInt(year) - 1);
        } else if (MyProjectConsts.Time_Type.Quarter.value().equals(type)){
            startTime = DateTimeUtils.getFirstDayOfQuarter(Integer.parseInt(year), Integer.parseInt(quarter));
            endTime = DateTimeUtils.getLastDayOfQuarter(Integer.parseInt(year), Integer.parseInt(quarter));
            lastStartTime = DateTimeUtils.getFirstDayOfQuarter(Integer.parseInt(year) - 1, Integer.parseInt(quarter));
            lastEndTime = DateTimeUtils.getLastDayOfQuarter(Integer.parseInt(year) - 1, Integer.parseInt(quarter));
        } else {
            startTime = DateTimeUtils.getFirstDayOfMonth(Integer.parseInt(year), Integer.parseInt(month));
            endTime = DateTimeUtils.getLastDayOfMonth(Integer.parseInt(year), Integer.parseInt(month));
            lastStartTime = DateTimeUtils.getFirstDayOfMonth(Integer.parseInt(year) - 1, Integer.parseInt(month));
            lastEndTime = DateTimeUtils.getLastDayOfMonth(Integer.parseInt(year) - 1, Integer.parseInt(month));
        }

        //当前时间完成量
        StatisticsCompleteVal currentCompleteVal = getCompleteVal(deptIds, salesmanId, startTime, endTime);
        //去年同期完成量
        StatisticsCompleteVal lastYearCompleteVal = getCompleteVal(deptIds, salesmanId, lastStartTime, lastEndTime);

        //1.签约面积
        BaseStatistics contractedArea = new BaseStatistics();
        //1.1部门计划签约面积指标
        Double areaCurrentTarget = 0.0;
        if(currentDeptPlanData != null){
            areaCurrentTarget = currentDeptPlanData.getContractedArea();
        }else if(currentSalesmanPlanData != null){
            areaCurrentTarget = currentSalesmanPlanData.getContractedArea();
        }
        contractedArea.setCurrentTarget(areaCurrentTarget == null?0.0:areaCurrentTarget);
        //1.2部门签约面积完成量
        Double areaCurrentComplete = currentCompleteVal.getContractedArea();
        contractedArea.setCurrentComplete(areaCurrentComplete);
        //1.3部门签约面积完成百分比
        if ( areaCurrentTarget == null || areaCurrentTarget == 0){
            contractedArea.setCurrentRate(0.0);
        }else {
            contractedArea.setCurrentRate(areaCurrentComplete / areaCurrentTarget);
        }
        //1.4部门签约面积同比变化量
        Double lastYearAreaComplete = lastYearCompleteVal.getContractedArea();
        if (lastYearAreaComplete == null || lastYearAreaComplete == 0) {
            if(areaCurrentComplete.doubleValue() != 0){
                contractedArea.setYearChange(1.0);
            }
        } else {
            Double areaYearChange = (areaCurrentComplete - lastYearAreaComplete) / lastYearAreaComplete;
            contractedArea.setYearChange(areaYearChange);
        }
        statistics.setContractedArea(contractedArea);

        //2.来访客户量
        BaseStatistics visitorCount = new BaseStatistics();
        //2.1部门计划来访客户量指标
        Integer visitorCurrentTarget = 0;
        if(currentDeptPlanData != null){
            visitorCurrentTarget = currentDeptPlanData.getVisitorCount();
        }else if(currentSalesmanPlanData != null){
            visitorCurrentTarget = currentSalesmanPlanData.getVisitorCount();
        }
        visitorCount.setCurrentTarget(visitorCurrentTarget == null?0.0:visitorCurrentTarget.doubleValue());
        //2.2部门来访客户量完成量
        Integer visitorCurrentComplete = currentCompleteVal.getVisitorCount();
        visitorCount.setCurrentComplete(visitorCurrentComplete == null?0.0:visitorCurrentComplete.doubleValue());
        //2.3部门来访客户量完成百分比
        if (visitorCurrentTarget == null || visitorCurrentTarget == 0 || visitorCurrentComplete == null){
            visitorCount.setCurrentRate(0.0);
        }else {
            visitorCount.setCurrentRate(visitorCurrentComplete/visitorCurrentTarget.doubleValue());
        }
        //2.4部门来访客户量同比变化量
        Integer lastYearVisitorCount = lastYearCompleteVal.getVisitorCount();
        if (lastYearVisitorCount == null || lastYearVisitorCount == 0){
            if(visitorCurrentComplete.intValue() != 0){
                visitorCount.setYearChange(1.0);
            }
        } else {
            double visitYearChange = ((visitorCurrentComplete == null?0.0:visitorCurrentComplete) - lastYearVisitorCount) / lastYearVisitorCount.doubleValue();
            visitorCount.setYearChange(visitYearChange);
        }
        statistics.setVisitorCount(visitorCount);

        //3.来电客户量
        BaseStatistics callerCount = new BaseStatistics();
        //3.1部门计划来电客户量指标
        Integer callerCurrentTarget = 0;
        if(currentDeptPlanData != null){
            callerCurrentTarget = currentDeptPlanData.getCallerCount();
        }else if(currentSalesmanPlanData != null){
            callerCurrentTarget = currentSalesmanPlanData.getCallerCount();
        }
        callerCount.setCurrentTarget(callerCurrentTarget == null?0.0:callerCurrentTarget.doubleValue());
        //3.2部门来电客户量完成量
        Integer callerCurrentComplete = currentCompleteVal.getCallerCount();
        callerCount.setCurrentComplete(callerCurrentComplete == null?0.0:callerCurrentComplete.doubleValue());
        //3.3部门来电客户量完成百分比
        if (callerCurrentTarget == null || callerCurrentTarget == 0 || callerCurrentComplete == null){
            callerCount.setCurrentRate(0.0);
        }else {
            callerCount.setCurrentRate(callerCurrentComplete.doubleValue() / callerCurrentTarget.doubleValue());
        }
        //3.4部门来电客户量同比变化量
        Integer lastYearCallerCount = lastYearCompleteVal.getCallerCount();
        if (lastYearCallerCount == null || lastYearCallerCount == 0){
            if(callerCurrentComplete.intValue() != 0){
                callerCount.setYearChange(1.0);
            }
        } else {
            Double callerYearChange = ((callerCurrentComplete == null?0.0:callerCurrentComplete) - lastYearCallerCount) / lastYearCallerCount.doubleValue();
            callerCount.setYearChange(callerYearChange);
        }
        statistics.setCallerCount(callerCount);

        //4.网络推广量（暂无数据来源，只显示指标）
        BaseStatistics networkPromotionCount = new BaseStatistics();
        Integer netWorkCurrentTarget = 0;
        if(currentDeptPlanData != null){
            netWorkCurrentTarget = currentDeptPlanData.getNetworkPromotionCount();
        }else if(currentSalesmanPlanData != null){
            netWorkCurrentTarget = currentSalesmanPlanData.getNetworkPromotionCount();
        }
        networkPromotionCount.setCurrentTarget(netWorkCurrentTarget == null?0.0:netWorkCurrentTarget.doubleValue());
        statistics.setNetworkPromotionCount(networkPromotionCount);
    }

    /**
     * @Description
     * @Param List<DeptPlanData> deptPlanDataList, List<BasePlan> basePlans, String timeType, String year, Long deptId
     * @Return null
     * @Date 2021/5/14 9:29
     */
    private void getDeptPlanData(List<DeptPlanData> deptPlanDataList, List<BasePlan> basePlans, String timeType, String year, Long deptId){
        for (BasePlan basePlan : basePlans) {
            DeptPlanData deptPlanData = new DeptPlanData();
            deptPlanData.setDeptId(deptId);
            deptPlanData.setType(timeType);
            deptPlanData.setYear(year);
            if (MyProjectConsts.Time_Type.Quarter.value().equals(timeType)){
                deptPlanData.setQuarter(basePlan.getTimeVal());
                deptPlanData.setMonth("0");
            } else if (MyProjectConsts.Time_Type.Month.value().equals(timeType)){
                deptPlanData.setMonth(basePlan.getTimeVal());
                deptPlanData.setQuarter("0");
            }else if (MyProjectConsts.Time_Type.Year.value().equals(timeType)){
                deptPlanData.setMonth("0");
                deptPlanData.setQuarter("0");
            }
            deptPlanData.setContractedArea(basePlan.getContractedArea());
            deptPlanData.setVisitorCount(basePlan.getVisitorCount());
            deptPlanData.setCallerCount(basePlan.getCallerCount());
            deptPlanData.setNetworkPromotionCount(basePlan.getNetworkPromotionCount());
            deptPlanDataList.add(deptPlanData);
        }
    }

    /**
     * @Description
     * @Param List<SalesmanPlanData> salesmanPlanDataList, List<BasePlan> basePlans, String timeType, String year, Long salesmanId
     * @Return null
     * @Date 2021/5/14 9:28
     */
    private void getSalesmanPlanData(List<SalesmanPlanData> salesmanPlanDataList, List<BasePlan> basePlans, String timeType, String year, Long salesmanId) throws ArgumentErrorException {
        Long headerUser = myHeaderUtil.getHeaderUser();
        if(headerUser == null){
            throw new ArgumentErrorException("登录信息已失效,请重新登录");
        }
        String orgIdStr = redisClient.get("Org:" + headerUser);
        for (BasePlan basePlan : basePlans) {
            SalesmanPlanData salesmanPlanData = new SalesmanPlanData();
            salesmanPlanData.setSalesmanId(salesmanId);
            salesmanPlanData.setOrgId(Long.parseLong(orgIdStr.split("-")[0]));
            salesmanPlanData.setType(timeType);
            salesmanPlanData.setYear(year);
            if(MyProjectConsts.Time_Type.Quarter.value().equals(timeType)){
                salesmanPlanData.setQuarter(basePlan.getTimeVal());
                salesmanPlanData.setMonth("0");
            } else if(MyProjectConsts.Time_Type.Month.value().equals(timeType)){
                salesmanPlanData.setMonth(basePlan.getTimeVal());
                salesmanPlanData.setQuarter("0");
            } else if(MyProjectConsts.Time_Type.Year.value().equals(timeType)){
                salesmanPlanData.setMonth("0");
                salesmanPlanData.setQuarter("0");
            }
            salesmanPlanData.setContractedArea(basePlan.getContractedArea());
            salesmanPlanData.setVisitorCount(basePlan.getVisitorCount());
            salesmanPlanData.setCallerCount(basePlan.getCallerCount());
            salesmanPlanData.setNetworkPromotionCount(basePlan.getNetworkPromotionCount());
            salesmanPlanDataList.add(salesmanPlanData);
        }
    }

    /**
     * @Description 查询当前登录人的组织(部门)以及子组织（部门）
     * @Param Long userId
     * @Return List<Long>
     * @Date 2021/5/12 15:09
     */
    private List<Long> subOrg(Long userId) {
        List<Long> orgIds = new ArrayList<>();
        String orgIdStr = redisClient.get("Org:" + userId);
        //获取当前登录人的组织
        if(!StringUtil.isEmpty(orgIdStr)){
            //查询当前组织以及子组织信息
            ResponseEntity<ResultObject> responseEntity = authorityClient.getSubOrg(orgIdStr);
            if(responseEntity != null){
                if(responseEntity.getStatusCode().is2xxSuccessful()){
                    Object results = responseEntity.getBody().getResults();
                    List<Organization> organizations = JSON.parseArray(JSON.toJSONString(results),Organization.class);
                    if (!CollectionUtil.isEmpty(organizations)) {
                        orgIds = organizations.stream().filter(organization -> organization.getId() != null)
                                .map(Organization::getId).collect(Collectors.toList());
                    }
                }
            }
        }
        return orgIds;
    }

    /**
     * @Description 根据厂房id获取厂房信息
     * @Param Long officeId
     * @Return Office
     * @Date 2021/5/12 15:07
     */
    private Office getOfficeById(Long officeId){
        Office office = new Office();
        ResponseEntity<ResultObject> responseEntity = authorityClient.getOfficeById(officeId);
        if(responseEntity != null){
            if(responseEntity.getStatusCode().is2xxSuccessful()){
                Object results = responseEntity.getBody().getResults();
                office = JSON.toJavaObject((JSON) JSON.toJSON(results),Office.class);
            }
        }
        return office;
    }

    /**
     * @Description 根据部门id和起止时间查询完成量（签约面积、来访客户量、来电客户量）
     * @Param Long deptId, String startTime, String endTime
     * @Return StatisticsCompleteVal
     * @Date 2021/5/13 14:24
     */
    private StatisticsCompleteVal getCompleteVal(List<Long> deptIds, Long salesmanId, String startTime, String endTime){
        StatisticsCompleteVal statisticsCompleteVal = new StatisticsCompleteVal();
        //1.签约面积
        List<Long> officeIds = myProjectRepository.getSuccessProjectByOrgIdSalesmanIdAndTime(MyProjectConsts.COMPANY_STATUS.Success.value(), deptIds, salesmanId, startTime, endTime);
        Double areaComplete = 0.0;
        for (int i = 0; i < officeIds.size(); i++) {
            Office office = getOfficeById(officeIds.get(i));
            if(office != null){
                areaComplete += office.getOfficeArea() == null?0.0:office.getOfficeArea();
            }

        }
        statisticsCompleteVal.setContractedArea(areaComplete);
        //2.来访客户量
        Integer visitorCount = processStatusRepository.getCountByOrgIdAndTime(deptIds, salesmanId, MyProjectConsts.COMPANY_STATUS.Visit.value(), startTime, endTime);
        statisticsCompleteVal.setVisitorCount(visitorCount);
        //3.来电客户量
        Integer phoneCount = processStatusRepository.getCountByOrgIdAndTime(deptIds, salesmanId, MyProjectConsts.COMPANY_STATUS.Phone.value(), startTime, endTime);
        statisticsCompleteVal.setCallerCount(phoneCount);
        //网络推广量（暂时无数据来源）

        return statisticsCompleteVal;
    }


}
